package com.yupi.yuojbackendcommon.manager;

/**
 * @Author FengHuan Wang
 * @Date 2025/3/12 19:55
 * @Version 1.0
 */

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;

import com.yupi.yuojbackendcommon.ai.AiResultMessage;
import com.yupi.yuojbackendcommon.config.AiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 阿里云百炼AI管理类
 */
@Slf4j
@Component
public class AiManager {

    @Resource
    private AiConfig aiConfig;

    private  GenerationResult callWithMessage(String question) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(question)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(aiConfig.getApiKey())
                .model(aiConfig.getModel())
                .messages(Arrays.asList(userMsg))
                // 不可以设置为"text"
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }

    /**
     * 调用Ai生成内容
     * @param question
     * @return
     */
    public AiResultMessage doGenerate(String question){
        String reasoningContent = null;
        String content = null;
        try {
            GenerationResult result = callWithMessage(question);
            log.info("思考过程：");
            reasoningContent = result.getOutput().getChoices().get(0).getMessage().getReasoningContent();
            log.info(reasoningContent);
            log.info("回复内容：");
            content = result.getOutput().getChoices().get(0).getMessage().getContent();
            log.info(content);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // 使用日志框架记录异常信息
            log.error("An error occurred while calling the generation service: ");
            e.printStackTrace();
        }
        // 把思考过程和回复内容封装成对象
        AiResultMessage aiResultMessage = AiResultMessage.builder()
                .processMessage(reasoningContent)
                .contentMessage(content)
                .build();
        return aiResultMessage;

    }
}
